import StringUtils from "../js/mod.string"

let f7 = null;
let initStorageObj = {
  // draft: {
  //   chat: [],
  //   approval: [],
  //   task: [],
  //   journal: [],
  // },
  // messageCenter: '',
  // theme: {
  //   bg: 'light',
  //   bar: 'blue',
  //   sys: 'md',
  // },
  // isStopJPush: false,
};

class Storage {
  static init(app) {
    f7 = app;
  }

  static set(key, val) {
    localStorage.setItem(key, val);
  }

  static get(key) {
    return localStorage.getItem(key);
  }

  static remove(key) {
    localStorage.removeItem(key);
  }

  static clear() {
    localStorage.clear();
  }

  static sessionSet(key, val) {
    sessionStorage.setItem(key, val);
  }

  static sessionGet(key) {
    return sessionStorage.getItem(key);
  }

  static sessionRemove(key) {
    sessionStorage.removeItem(key);
  }

  static sessionClear() {
    sessionStorage.clear();
  }

  /**
   * 获取某一模块的本地存储
   * @param _module all 获取全部本地数据；对应 module 时，获取对应 module 的本地数据
   * @param _handler 获取成功后处理函数
   */
  static getLocalDataByModule(_module) {
    let _this = this;
    return new Promise((resolve, reject) => {

      let storageKey = f7.data['logged-in-user'] ? f7.data['logged-in-user']
          : '';
      let moduleData = null;
      if (storageKey == '') {
        resolve(moduleData);
        // _handler(moduleData);
      } else {
        let localStr = _this.get(storageKey);
        localStr = localStr ? localStr : '';
        let localObj = {};
        if (localStr == '') {
          localObj = initStorageObj;
          localStr = StringUtils.toStr(localObj);
          _this.set(storageKey, localStr);
        }
        localObj = StringUtils.toJson(localStr);
        // if (_handler && typeof _handler == "function") {
        let moduleArr = _module.split('.');
        let moduleLen = moduleArr.length;
        if (moduleLen > 0) {
          if (moduleLen == 1) {
            switch (_module) {
              case 'all':
                moduleData = localObj;
                break;
              default:
                moduleData = localObj[_module] ? localObj[_module] : null;
                break;
            }
          } else if (moduleLen == 2) {
            moduleData = (localObj[moduleArr[0]]
                ? (localObj[moduleArr[0]][moduleArr[1]]
                    ? localObj[moduleArr[0]][moduleArr[1]] : null) : null);
          }
        }
        resolve(moduleData);
        // _handler(moduleData);
        // }
      }
    });
  }

  /**
   * 更新某一模块的本地存储
   * @param _module all 更新全部本地数据；对应 module 时，更新对应 module 的本地数据
   * @param _data 要保存的数据，数组格式
   */
  static updateLocalDataByModule(_module, _data) {
    let _this = this;
    let storageKey = f7.data['logged-in-user'] ? f7.data['logged-in-user'] : '';
    if (_module != 'all') {
      let localStr = _this.get(storageKey);
      localStr = localStr ? localStr : '';
      let localObj = {};
      if (localStr == '') {
        localObj = initStorageObj;
        localStr = StringUtils.toStr(localObj);
        _this.set(storageKey, localStr);
      }
      localObj = StringUtils.toJson(localStr);
      let resObj = {};

      let moduleArr = _module.split('.');
      let moduleLen = moduleArr.length;
      if (moduleLen > 0) {
        switch (moduleLen) {
          case 1:
            if (localObj[_module]) {
              for (let i in localObj) {
                let item = localObj[i];
                if (i == _module) {
                  item = _data;
                }
                resObj[i] = item;
              }
            } else {
              resObj = localObj;
              resObj[_module] = _data;
            }
            break;
          case 2:
            if (localObj[moduleArr[0]]) {
              if (localObj[moduleArr[0]][moduleArr[1]]) {
                for (let i in localObj) {
                  let item = localObj[i];
                  if (i == moduleArr[0]) {
                    let resSubObj = {};
                    for (let x in localObj[i]) {
                      let subItem = localObj[i][x];
                      if (x == moduleArr[1]) {
                        subItem = _data;
                      }
                      resSubObj[x] = subItem;
                    }
                    if (resSubObj.length == 0) {
                      continue;
                    }
                    item = resSubObj;
                  }
                  resObj[i] = item;
                }
              } else {
                resObj = localObj;
                resObj[moduleArr[0]][moduleArr[1]] = _data;
              }

            } else {
              resObj = localObj;
              resObj[moduleArr[0]] = {};
              resObj[moduleArr[0]][moduleArr[1]] = _data;
            }
            break;
        }
      } else {
        resObj = localObj;
      }
      _this.set(storageKey, StringUtils.toStr(resObj));
    } else {
      _this.set(storageKey, StringUtils.toStr(_data));
    }
  }

  /**
   * 删除对应 _module 的本地存储
   * @param _module
   * @returns {{}}
   */
  static deleteLocalDataByModule(_module) {
    let _this = this;
    let storageKey = f7.data['logged-in-user'] ? f7.data['logged-in-user'] : '';
    let resObj = {};
    if (_module != 'all') {

      let localStr = _this.get(storageKey);
      localStr = localStr ? localStr : '';
      let localObj = {};
      if (localStr == '') {
        localObj = initStorageObj;
        localStr = StringUtils.toStr(localObj);
        _this.set(storageKey, localStr);
      }
      localObj = StringUtils.toJson(localStr);
      let moduleArr = _module.split('.');
      let moduleLen = moduleArr.length;
      if (moduleLen > 0) {
        switch (moduleLen) {
          case 1:
            if (localObj[_module]) {
              for (let i in localObj) {
                let item = localObj[i];
                if (i == _module) {
                  continue;
                }
                resObj[i] = item;
              }
            } else {
              resObj = localObj;
            }
            break;
          case 2:
            if (localObj[moduleArr[0]]) {

              if (localObj[moduleArr[0]][moduleArr[1]]) {
                for (let i in localObj) {
                  let item = localObj[i];
                  if (i == moduleArr[0]) {
                    let resSubObj = {};
                    for (let x in localObj[i]) {
                      let subItem = localObj[i][x];
                      if (x == moduleArr[1]) {
                        continue;
                      }
                      resSubObj[x] = subItem;
                    }
                    if (resSubObj.length == 0) {
                      continue;
                    }
                    item = resSubObj;
                  }
                  resObj[i] = item;
                }
              } else {
                resObj = localObj;
              }

            } else {
              resObj = localObj;
            }
            break;
        }
      } else {
        resObj = localObj;
      }
      _this.set(storageKey, StringUtils.toStr(resObj));

    } else {
      resObj = null;
      _this.remove(storageKey);
    }
    return resObj;
  }

  /**
   * 检查数组 _arr 中是否包含有 _id 对应的记录
   * @param _id
   * @param _arr
   * @param _handler
   */
  static checkDataIsExistById(_id, _arr) {
    return new Promise((resolve, reject) => {
      if (_arr && _arr.length > 0) {
        let ids = [];
        for (let i in _arr) {
          if (!_arr[i].id) {
            continue;
          }
          ids.push(_arr[i].id);
        }
        (ids.indexOf(_id) > -1) ? resolve(true) : resolve(false);
        // if (ids.indexOf(_id) > -1) {
        // if (_handler && typeof _handler == "function") {
        //   _handler(true);
        // }
        // } else {
        // _handler(false);
        // }
      } else {
        resolve(false);
        // _handler(false);
      }
    });
  }

  /**
   * 更新或添加数组 _arr 中 _id 对应的记录值为 _data
   * @param _id
   * @param _arr
   * @param _data
   * @returns {Promise<any>} : 结果数组
   */
  static updateDataById(_id, _arr, _data) {
    let _this = this;
    let resArr = [];
    _arr = _arr ? _arr : [];
    return new Promise((resolve, reject) => {
      _this.checkDataIsExistById(_id, _arr)
      .then(isExisted => {
        if (isExisted) {
          let afterArr = [];
          for (let i in _arr) {
            let item = _arr[i];
            if (!_arr[i].id) {
              continue;
            }
            if (_arr[i].id == _id) {
              item = _data;
            } else {
              item = _arr[i];
            }
            afterArr.push(item);
          }
          resArr = afterArr;
        } else {
          resArr = _arr;
          resArr.push(_data);
        }
        resolve(resArr);
      });
    });
  }

  /**
   * 删除数组 _arr 中对应 _id 的记录
   * @param _id
   * @param _arr
   * @returns {Array} : 结果数组
   */
  static deleteDataById(_id, _arr) {
    let _this = this;
    let resArr = [];
    _arr = _arr ? _arr : [];
    _this.checkDataIsExistById(_id, _arr)
    .then(isExisted => {
      if (isExisted) {
        let afterArr = [];
        for (let i in _arr) {
          let item = _arr[i];
          if (!_arr[i].id) {
            continue;
          }
          if (_arr[i].id != _id) {
            afterArr.push(item);
          }
        }
        resArr = afterArr;
      } else {
        resArr = _arr;
      }
    });
    return resArr;
  }

  /**
   * 获取数组 _arr 中对应 _id 的记录
   * @param _id
   * @param _arr
   * @param _handler
   */
  static getDataById(_id, _arr) {
    let _this = this;
    _arr = _arr ? _arr : [];
    return new Promise((resolve, reject) => {
      _this.checkDataIsExistById(_id, _arr)
      .then(isExist => {
        let resData = null;
        if (isExist) {
          for (let i in _arr) {
            if (!_arr[i].id) {
              continue;
            }
            if (_arr[i].id == _id) {
              resData = _arr[i];
              break;
            }
          }
        }
        resolve(resData);
        // if (_handler && typeof _handler == "function") {
        //   _handler(null);
        // }
      });
    });
  }

  /**
   * 增加或更新某个 module 当中对应 id 的数据
   * @param _module
   * @param _id
   * @param _data
   */
  static updateLocalDataByModuleAndId(_module, _id, _data) {
    let _this = this;
    _this.getLocalDataByModule(_module)
    .then(moduleArr => _this.updateDataById(_id, moduleArr, _data))
    .then(afterModuleData => {
      _this.updateLocalDataByModule(_module, afterModuleData);
    });
    // .then(moduleArr => {
    //   let afterModuleData = _this.updateDataById(_id, moduleArr, _data);
    //   _this.updateLocalDataByModule(_module, afterModuleData);
    // });
  }

  /**
   * 删除某个 module 当中对应 id 的数据
   * @param _module
   * @param _id
   * @param _data
   */
  static deleteLocalDataByModuleAndId(_module, _id) {
    let _this = this;
    _this.getLocalDataByModule(_module)
    .then(moduleArr => {
      let afterModuleData = _this.deleteDataById(_id, moduleArr);
      _this.updateLocalDataByModule(_module, afterModuleData);
    });
  }

  /**
   * 获取某个 module 当中对应 id 的数据
   * @param _module
   * @param _id
   * @param _handler
   */
  static getLocalDataByModuleAndId(_module, _id) {
    let _this = this;
    return new Promise((resolve, reject) => {
      _this.getLocalDataByModule(_module)
      .then(moduleData => _this.getDataById(_id, moduleData))
      .then(data => resolve(data))
    });
  }
}

export default Storage;
